Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

[productId].ts 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const Product = require('../../../models/product');
  2. import dbConnect from '../../../utils/helpers/dbHelpers';
  3. import type { NextApiRequest, NextApiResponse } from 'next';
  4. import {
  5. ProductDataDB,
  6. SingleProductResponse,
  7. } from '../../../utils/interface/productInterface';
  8. async function handler(
  9. req: NextApiRequest,
  10. res: NextApiResponse<SingleProductResponse>
  11. ) {
  12. const { method } = req;
  13. await dbConnect();
  14. switch (method) {
  15. case 'GET': {
  16. try {
  17. const productId = req.query.productId;
  18. const product: ProductDataDB = await Product.findOne({
  19. customID: productId,
  20. });
  21. if (!product) {
  22. throw new Error('The product with this id does not exist!');
  23. }
  24. const similarProducts: Array<ProductDataDB> = await Product.find({
  25. category: product.category,
  26. customID: { $ne: product.customID },
  27. });
  28. const shuffled = similarProducts
  29. .sort(() => 0.5 - Math.random())
  30. .slice(0, 3);
  31. res.status(200).json({
  32. message: 'The product you requested was fetched successfully.',
  33. product,
  34. similarProducts: shuffled,
  35. });
  36. } catch (error) {
  37. if (error instanceof Error)
  38. res.status(400).json({ message: error.message });
  39. else res.status(400).json({ message: 'Unexpected error' + error });
  40. }
  41. break;
  42. }
  43. default:
  44. res.status(405).json({ message: 'Method not allowed' });
  45. break;
  46. }
  47. }
  48. export default handler;